#!/usr/bin/python
# -*- coding: utf-8 -*-
# @Project    : AutomatedTesting
# @Name       : error_handle.py
# @IDE        : PyCharm
# @Author     : OneYoung
# @Created    : 2025/8/24 20:19
# @Desc       : 异常捕获装饰器

import os.path
import allure
from functools import wraps
from utils.log_record import logger, log_path
from utils.get_time import digital_datetime


def exception_monitor(func):
    """
    异常监控装饰器，出现异常后截图并添加到Allure报告中

    :param func: 执行函数
    :return:
    """

    @wraps(func)  # 消除装饰器对原函数造成的影响
    def monitor(*args, **kwargs):
        try:
            return func(*args, **kwargs)
        except Exception as ec:
            # 获取到浏览器驱动
            for key, value in kwargs.items():
                try:
                    driver = kwargs[key].driver
                    # 保存异常截图
                    file_path = os.path.join(log_path, 'error')
                    if not os.path.exists(file_path):
                        os.mkdir(file_path)
                    file_name = os.path.join(file_path, f'{digital_datetime()}-error.png')
                    # 截图
                    driver.save_screenshot(file_name)
                    # 将异常截图添加到Allure报告中
                    allure.attach.file(
                        source=file_name,
                        name=f"{digital_datetime()}-ERROR",
                        attachment_type=allure.attachment_type.PNG
                    )
                    break
                except AttributeError:
                    continue
            logger.error(f"用例执行失败,截图并添加到Allure报告: {ec}")
            # 操作执行完成后抛出异常，否则错误被捕获，用例会判定为通过
            raise ec

    return monitor
